/**
 *  Excel导入导出服务
 *
 */
define(['app','filesaver'], function( app ) {
    'use strict';

    app.factory('excel', ['dataFactoryCRM','$rootScope', function (dataFactoryCRM, $rootScope) {
        var excel = {version:0.01,sheets:[]};

        var tmplWorkbookXML = '<?xml version="1.0"?><?mso-application progid="Excel.Sheet"?>'
              +'<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">'
              + '<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"><Author>ZhangYe</Author><Created>{created}</Created></DocumentProperties>'
              + '<Styles>'
              + '<Style ss:ID="Currency"><NumberFormat ss:Format="Currency"></NumberFormat></Style>'
              + '<Style ss:ID="Date"><NumberFormat ss:Format="Medium Date"></NumberFormat></Style>'
              + '</Styles>'
              + '{worksheets}</Workbook>'
            , tmplWorksheetXML = '<Worksheet ss:Name="{nameWS}"><Table>{rows}</Table></Worksheet>'
            , tmplCellXML = '<Cell{attributeStyleID}{attributeFormula}><Data ss:Type="{nameType}">{data}</Data></Cell>';


        excel.add_sheet = function( _title, _fields, _data ){
            var _t = {};
            _t.title = _title;
            _t.fields = _fields;
            _t.data = _data;
            excel.sheets.push( _t );
        }

        excel.format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
        excel.base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }

        excel.export =  function( _title ) {
            if( !this.sheets || this.sheets.length < 1 )
                return false;
            var ctx = "";
            var workbookXML = "";
            var worksheetsXML = "";
            var rowsXML = "";
            var rowdata = null;

            for (var i = 0; i < this.sheets.length; i++) {
                this.sheets[i].data.unshift( this.sheets[i].fields );
                for (var j = 0; j < this.sheets[i].data.length; j++) {
                    rowsXML += '<Row>';
                    for (var k = 0; k < this.sheets[i].data[j].length; k++) {
                        var dataValue = this.sheets[i].data[j][k];
                        ctx = {  attributeStyleID:''
                               , nameType:'String'
                               , data: (dataValue)? dataValue : ''
                               , attributeFormula:''
                              };
                        rowsXML += this.format(tmplCellXML, ctx);
                   }
                  rowsXML += '</Row>'
                }
                ctx = {rows: rowsXML, nameWS: this.sheets[i].title || 'Sheet' + i};
                worksheetsXML += this.format(tmplWorksheetXML, ctx);
                rowsXML = "";
              }

              ctx = {created: (new Date()).getTime(), worksheets: worksheetsXML};
              workbookXML = this.format(tmplWorkbookXML, ctx);

              if( _title ) _title + '.xls';
              var download = _title || 'Workbook.xls';

              var blob = new Blob([ workbookXML], {
                    type: "application/vnd.ms-excel;charset=charset=utf-8"
                });
                saveAs(blob,  download);
            }

        excel.import = function( _data ){
            //
        }

        return excel;
    }]);
});